package com.bprogram.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class IdGenerator {

    //当前机器的机器码
    private long workId = 0l;
    //时间戳
    private long datacenterId = 1l;

    private Snowflake snowflake = IdUtil.createSnowflake(workId, datacenterId);

    @PostConstruct
    public void init() {
        try {
            workId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        } catch (Exception e) {
            workId = NetUtil.getLocalhostStr().hashCode();
            e.printStackTrace();
        }
    }

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }


    public synchronized long snowflakeId(long workId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workId, datacenterId);
        return snowflake.nextId();
    }


}
